<template>
    <div class="baseinfo-form">
        <el-form :rules="rules" ref="elForm" :model="mobileForm" label-width="130px" :validate-on-rule-change="false">
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="code" label="功能ID">
                        <el-input :disabled="codeDisabled" placeholder="请输入数字，数字为4位数，如：0001" size="small"
                            v-model.trim="mobileForm.code">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="name" label="功能名称">
                        <el-input placeholder="请输入，最多不超过20字" maxlength="20" size="small" v-model="mobileForm.name">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="type" label="功能分类">
                        <el-select v-model="mobileForm.type" placeholder="请选择">
                            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="sort_code" label="排序">
                        <el-input placeholder="请输入，最多不超过20字" size="small" v-model="mobileForm.sort_code"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="implement_type" label="功能实现方式">
                        <el-select v-model="mobileForm.implement_type" placeholder="请选择">
                            <el-option v-for="item in implementOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="mobileForm.implement_type == 'html_5' || mobileForm.implement_type == 'H5'" key="h5_1">
                <el-col :span="24">
                    <el-form-item prop="redirect_url" label="页面跳转链接" :rules="[
                        { required: true, message: '请输入跳转链接' }
                    ]">
                        <el-input type="textarea" placeholder="请输入" :rows="3" size="small"
                            v-model="mobileForm.redirect_url"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="mobileForm.implement_type == 'protogenesis' || mobileForm.implement_type == '原生'"
                key="implement_1">
                <el-col :span="24">
                    <el-form-item prop="name" label="page_name_ios" :rules="[
                        { required: true, message: '请输入 name 字段' }
                    ]">
                        <el-input placeholder="请输入" size="small" v-model="mobileForm.ios_path"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="mobileForm.implement_type == 'protogenesis' || mobileForm.implement_type == '原生'"
                key="implement_2">
                <el-col :span="24">
                    <el-form-item prop="name" label="page_name_android" :rules="[
                        { required: true, message: '请输入 name 字段' }
                    ]">
                        <el-input placeholder="请输入" size="small" v-model="mobileForm.android_path"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="icon_path" label="图标文件">
                        <el-upload ref="elFile" class="upload-icon" :on-change="fileChange" :file-list="fileList"
                            list-type="picture-card" :auto-upload="false" :limit="1" :on-exceed="fileExceed"
                            :on-remove="fileRemove" accept=".png">
                            <i class="el-icon-plus"></i>
                            <span>点击上传图片</span>
                            <div slot="tip" class="el-upload__tip">仅支持上传2倍图，尺寸100 * 100；支持.png 类型文件，2M以内</div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item prop="is_show" label="显示状态">
                        <el-switch v-model="mobileForm.is_show" :active-value="1" :inactive-value="0">
                        </el-switch>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import {
    addAppFunc,
    updateAppFunc,
} from "@/api/organization/iphoneFunc";
import { getDataItem } from '@/api/system/dataitem'
import { validateMobSort, validateMobSortFour } from '@/api/organization/validateFunc';
import { baseUrl } from "@/config/env";
import axios from 'axios'
export default {
    name: "AddMobileFunc",
    props: {
        FuncId: {
            type: String,
        },
        menuTreeData: {
            type: Object,
            default() {
                return {}
            }
        },
        mobileForm: {
            type: Object,
            default: function () {
                return {
                    menu_type_id: '',
                    code: "", // 功能ID
                    name: '', // 功能名称
                    type: '', // 功能分类
                    sort_code: "", // 排序
                    implement_type: "", // 功能实现方式, H5 or 原生
                    redirect_url: '', // 页面跳转链接  h5 就显示这个
                    ios_path: '', // page_name_ios 原生展示这个
                    android_path: '', // page_name_android 原生展示这个
                    icon_path: '', // 图标文件
                    is_show: '1', // 显隐状态
                    icon_full_path: '', // 编辑显示图片用的,其他地方不用
                };
            },
        }
    },
    data() {
        return {
            typeOptions: [], // 功能类型
            implementOptions: [], // 功能实现方式
            fileList: [],//文件存储中间量
            codeDisabled: false,
            rules: {
                code: [
                    { required: true, message: '请输入功能ID', trigger: "blur" },
                    { validator: validateMobSortFour, trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入功能名称', trigger: "blur" },
                ],
                type: [
                    { required: true, message: '请选择功能分类', trigger: "change" },
                ],
                sort_code: [
                    { required: true, message: '请输入数字', trigger: "blur" },
                    { validator: validateMobSort, trigger: 'blur' }
                ],
                implement_type: [
                    { required: true, message: '请选择', trigger: "change" },
                ],
                icon_path: [
                    { required: true, message: '请选择上传图标', trigger: 'change' }
                ],
                is_show: [{ required: true, message: '请选择', trigger: "change" }]
            },
        };
    },
    created() {
        this.mobileForm.menu_type_id = this.menuTreeData.F_ItemDetailId // 点击菜单id
        this.getTypeData()
        if (!this.FuncId) {
            this.codeDisabled = false
            this.fileList = []
        } else {
            this.fileList.push({ url: this.mobileForm.icon_full_path })
            this.codeDisabled = true // 功能ID 编辑时禁用
        }
        console.log(this.mobileForm.type, this.typeOptions, '弹窗');
    },
    methods: {
        // 获取功能分类列表
        getTypeData() {
            getDataItem("AppFunctionType").then((res) => {
                if (res.data && res.data.code == 0) {
                    if (this.menuTreeData.F_ItemName == 'OA审批') {
                        this.typeOptions = []
                        res.data.data.forEach((ele) => {
                            this.typeOptions.push({
                                value: ele.F_ItemValue,
                                label: ele.F_ItemName
                            })
                        })
                    } else {
                        this.typeOptions = [{
                            value: '-',
                            label: '-'
                        }]
                    }
                }
            });
            getDataItem("AppFunctionImplemented").then((res) => {
                if (res.data && res.data.code == 0) {
                    this.implementOptions = []
                    res.data.data.forEach((ele) => {
                        this.implementOptions.push({
                            value: ele.F_ItemValue,
                            label: ele.F_ItemName
                        })
                    })
                }
            });
        },
        fileChange(file) {
            let fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()

            const isPNG = fileType === 'png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isPNG) {
                this.$notify.warning('上传头像图片只能是 PNG 格式!');
                this.mobileForm.icon_path = ''
                this.fileList = []
                return false
            }
            if (!isLt2M) {
                this.$notify.warning('上传头像图片大小不能超过 2MB!');
                this.mobileForm.icon_path = ''
                this.fileList = []
                return false
            }

            let isSize = new Promise((resolve, reject) => {
                const _URL = window.URL || window.webkitURL
                const img = new Image()
                let obj = {
                    imgWidth: 0,
                    imgHeight: 0
                }
                img.onload = function () {
                    obj.imgWidth = img.width
                    obj.imgHeight = img.height
                    const status = img.width === 100 && img.height === 100
                    status ? resolve() : reject(obj)
                }
                img.src = _URL.createObjectURL(file.raw)
            })
                .then(() => {
                    this.sendFile(file)
                })
                .catch((obj) => {
                    this.$nextTick(() => {
                        this.$refs.elFile.clearFiles()
                        this.$notify.warning(`图片尺寸限制为 100 * 100，您上传的图片为${obj.imgWidth} * ${obj.imgHeight}`);
                    })
                })
        },
        sendFile(file) {
            let formData = new FormData();//new一个表单对象
            formData.append("file", file.raw);
            axios({
                method: 'post',
                url: `${baseUrl}/upload/oss`,
                headers: { 'Content-Type': 'multipart/form-data' },
                data: formData
            }).then(res => {
                if (res.data.success) {
                    let resData = res.data.data
                    this.$notify.success('图片上传成功')
                    this.mobileForm.icon_path = resData.fileRelativePath
                }
            })
        },
        // 上传个数限制
        fileExceed() {
            this.$notify({
                title: '提示',
                message: '最多上传一张图片',
                type: "warning",
            })
        },
        fileRemove() {
            this.mobileForm.icon_path = ''
        },
        // 提交表单
        async userFormSubmit(callback) {
            this.valid = this.validateData();
            if (this.valid) {
                try {
                    if (this.FuncId) {
                        let result = await updateAppFunc(this.FuncId, { xjr_oa_app_functionEntity: this.mobileForm });
                        let res = result.data;
                        if (res.success) {
                            if (callback) {
                                callback(res.data);
                            }
                        }
                    } else {
                        // 添加
                        let result = await addAppFunc({ xjr_oa_app_functionEntity: this.mobileForm });
                        let res = result.data;
                        if (res.success) {
                            if (callback) {
                                callback(res.data);
                            }
                        } else {
                            this.$notify({
                                title: this.$t('deletePrompt.promptTitle'),
                                message: this.$t('workFlow.addStamp.hintAddFailure'),
                                type: "success",
                            });
                        }

                    }
                } catch (error) {

                }

            }
        },
        /* 提交表单 */
        validateData() {
            let flag = false;
            this.$refs["elForm"].validate((valid) => {
                flag = valid;
            });
            return flag;
        },
    }
}
</script>
<style lang="scss" scoped>
.upload-icon {
    display: flex;

    ::v-deep .el-upload--picture-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        line-height: normal;
    }
    .el-upload__tip{
        transform: translate(10px, 64px)
    }
}
</style>